/*
 * @Author: Eli.Chen
 * @Date: 2025-04-27 14:36:46
 * @LastEditors: Eli.Chen
 * @LastEditTime: 2025-04-27 18:00:47
 * @Description:
 */
import { useState, useEffect } from 'react';
import { Avatar, Upload, Descriptions, Input, Button, Select, message, Checkbox } from 'antd';
import { FormOutlined, CameraOutlined } from '@ant-design/icons';
import { useSelector, useDispatch } from 'react-redux';

import { getUserProfile, getAvatarPath, uploadAvatar, updateUserProfile } from '@/api/user';
import { getCityList } from '@/api/city';
import { storage } from '@/utils/storage';
import { setUserIsRefresh } from '@/store/reducers/active';
import { COLOR_THEME } from '@/config/theme';
import { urlMap, imagesMap } from '@/utils';

const items1 = [
    {
        key: '1',
        label: '用户名',
    },
    {
        key: '2',
        label: '性别',
    },
    {
        key: '3',
        label: '邮箱',
    },
    {
        key: '4',
        label: '所在地区',
    },
    {
        key: '5',
        label: '个性签名',
        span: 2,
    },
    {
        key: '6',
        label: '个人简介',
        span: 2,
    },
    {
        key: '7',
        label: '感兴趣的文化习俗',
        span: 2,
    },
];
const CULTURAL_TYPES = [
    { label: '传统建筑', value: 1 },
    { label: '特色美食', value: 2 },
    { label: '地方习俗', value: 3 },
    { label: '手工艺', value: 4 },
    { label: '传统服饰', value: 5 },
];
const baseItems = [
    { label: '用户名', field: 'username' },
    { label: '性别', field: 'sex' },
    { label: '邮箱', field: 'email' },
    { label: '所在地区', field: 'cityName' },
    { label: '个性签名', field: 'signature', span: 2 },
    { label: '个人简介', field: 'profile', span: 2 },
    { label: '感兴趣的文化习俗', field: 'interestedCulture', span: 2 },
];
export default function EditProfile() {
    const { userInfo } = useSelector((state) => state.auth);
    const [userProfile, setUserProfile] = useState([]);
    const [avatarPath, setAvatarPath] = useState('');
    const [items, setItems] = useState(items1);
    const [cityData, setCityData] = useState([]);
    const [isEditing, setIsEditing] = useState(false);
    const [formData, setFormData] = useState(() => Object.fromEntries(items1.map((item) => [item.key, item.children])));
    const dispatch = useDispatch();

    const beforeUpload = (file) => {
        const isImage = file.type.startsWith('image/');
        if (!isImage) {
            message.error('仅支持图片格式');
        }
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt5M) {
            message.error('图片大小不能超过5MB');
        }
        return isImage && isLt5M;
    };

    const handleAvatarUpload = async (file) => {
        try {
            const formData = new FormData();
            formData.append('avatar', file);
            const response = await uploadAvatar(userInfo.userId, formData);
            if (response.code === 200) {
                setAvatarPath(response?.data);
                message.success('头像更新成功');
            }
        } catch (error) {
            console.error('头像上传失败:', error);
            message.error('头像上传失败');
        }
    };

    const getUserProfileInfo = async () => {
        try {
            const response = await getUserProfile(userInfo.userId);
            if (response.code === 200) {
                const formattedItems = baseItems.map((item, index) => ({
                    key: String(index + 1),
                    label: item.label,
                    children:
                        item.field === 'interestedCulture'
                            ? response.data[item.field]
                                ? response.data[item.field]
                                      .split(',')
                                      .map((v) => {
                                          const type = CULTURAL_TYPES.find((t) => t.value === parseInt(v));
                                          return type ? type.label : null;
                                      })
                                      .filter(Boolean)
                                      .join('，')
                                : '暂未填写'
                            : response.data[item.field] || '暂未填写',
                }));
                const initialFormData = baseItems.reduce((acc, item, index) => {
                    acc[String(index + 1)] = response.data[item.field] || '';
                    return acc;
                }, {});
                setFormData(initialFormData);
                setUserProfile(formattedItems);
            }
        } catch (error) {
            console.error('获取用户信息失败:', error);
        }
    };
    const getUserAvatarPath = async () => {
        try {
            const response = await getAvatarPath(userInfo.userId);
            if (response.code === 200 && response?.data) {
                setAvatarPath(response?.data);
                // dispatch(setUserIsRefresh(true));
                // storage.setItem(storage.keys.USER_INFO, { ...userInfo, avatarPath: response?.data });
            }
        } catch (error) {
            console.error('获取用户头像信息失败:', error);
        }
    };
    const getCity = () => {
        try {
            getCityList().then((res) => {
                if (res.code === 200) {
                    const cityList = res.data;
                    setCityData(cityList);
                }
            });
        } catch (error) {
            console.error('获取城市信息失败:', error);
        }
    };

    useEffect(() => {
        getUserProfileInfo();
        getUserAvatarPath();
        getCity();
    }, [userInfo]);

    return (
        <div
            style={{
                width: '100%',
                height: '100%',
                flexDirection: 'column',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                position: 'relative',
            }}
        >
            <div
                style={{
                    textAlign: 'center',
                    marginBottom: 0,
                    position: 'relative',
                }}
            >
                <Upload
                    name="avatar"
                    showUploadList={false}
                    beforeUpload={beforeUpload}
                    disabled={!isEditing}
                    customRequest={({ file }) => handleAvatarUpload(file)}
                >
                    <Avatar
                        size={128}
                        src={urlMap.defaultUrl + imagesMap.defaultAvatarPath + userInfo?.userId + '/' + avatarPath}
                        style={{
                            border: `2px solid ${COLOR_THEME.PRIMARY}`,
                            cursor: isEditing ? 'pointer' : 'default',
                        }}
                    />
                    {isEditing && (
                        <div
                            style={{
                                position: 'absolute',
                                bottom: 0,
                                right: '35%',
                                background: '#1890ff',
                                borderRadius: '50%',
                                padding: 4,
                                cursor: 'pointer',
                            }}
                        >
                            <CameraOutlined style={{ fontSize: 20, color: 'white' }} />
                        </div>
                    )}
                </Upload>
            </div>
            {!isEditing && (
                <Button
                    icon={<FormOutlined />}
                    style={{
                        position: 'absolute',
                        right: 20,
                        top: 20,
                        zIndex: 1,
                    }}
                    onClick={() => setIsEditing(true)}
                />
            )}
            <Descriptions
                items={userProfile?.map((item) => ({
                    ...item,
                    span: ['个性签名', '个人简介'].includes(item.label) ? 2 : 1,
                    children: isEditing ? (
                        ['用户名', '邮箱'].includes(item.label) ? (
                            item.children
                        ) : item.label === '性别' ? (
                            <Select
                                value={formData[item.key]}
                                onChange={(value) => setFormData({ ...formData, [item.key]: value })}
                                options={[
                                    { value: '男', label: '男' },
                                    { value: '女', label: '女' },
                                ]}
                                style={{ width: '100%' }}
                            />
                        ) : item.label === '所在地区' ? (
                            <Select
                                value={formData[item.key]}
                                onChange={(value) => setFormData({ ...formData, [item.key]: value })}
                                options={cityData?.map((city) => ({
                                    value: city?.cityId,
                                    label: city?.cityName,
                                }))}
                                style={{ width: '100%' }}
                            />
                        ) : item.label === '感兴趣的文化习俗' ? (
                            <Checkbox.Group
                                options={CULTURAL_TYPES}
                                value={formData[item.key]?.split(',').map(Number) || []}
                                onChange={(values) =>
                                    setFormData({
                                        ...formData,
                                        [item.key]: values.join(','),
                                    })
                                }
                            />
                        ) : item.label === '个人简介' ? (
                            <Input.TextArea
                                value={formData[item.key]}
                                onChange={(e) => setFormData({ ...formData, [item.key]: e.target.value })}
                                rows={4}
                            />
                        ) : (
                            <Input
                                value={formData[item.key]}
                                onChange={(e) => setFormData({ ...formData, [item.key]: e.target.value })}
                            />
                        )
                    ) : (
                        item.children
                    ),
                }))}
                column={2}
                style={{
                    width: '76%',
                    marginTop: 30,
                }}
            />

            {isEditing && (
                <div style={{ marginTop: 20, display: 'flex', gap: 16 }}>
                    <Button
                        type="primary"
                        onClick={async () => {
                            try {
                                const updateData = {
                                    userId: userInfo.userId,
                                    ...Object.entries(formData).reduce((acc, [key, value]) => {
                                        const mapping = {
                                            1: 'username',
                                            2: 'sex',
                                            3: 'email',
                                            4: 'cityId',
                                            5: 'signature',
                                            6: 'profile',
                                            7: 'interestedCulture',
                                        };
                                        if (mapping[key] && value) acc[mapping[key]] = value;
                                        return acc;
                                    }, {}),
                                };
                                console.log('updateData', updateData);

                                // 调用更新接口
                                const res = await updateUserProfile(updateData);

                                if (res.code === 200) {
                                    message.success('资料更新成功');
                                    // 刷新本地数据
                                    await getUserProfileInfo();
                                    setIsEditing(false);
                                }
                            } catch (error) {
                                message.error('保存失败，请稍后重试');
                            }
                        }}
                    >
                        保存
                    </Button>
                    <Button
                        onClick={() => {
                            setIsEditing(false);
                            // setFormData(Object.fromEntries(items1.map(item => [item.key, item.children])));
                        }}
                    >
                        取消
                    </Button>
                </div>
            )}
        </div>
    );
}
